﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using HCI.Questionaire.Exceptions;
using HCI.Questionaire.QuestionGroup;
using System.ComponentModel;
using System.Windows.Media;
using HCI.Questionaire.Controls;
using System.Windows.Media.Imaging;

namespace HCI.Questionaire
{
    public partial class QuestionContainerPage : Page
    {
        #region Faild
        private QuestionGroupHeader _QuestionGroupHeaderControl;
        private Canvas _currentTab;
        private Canvas _fieldTab;
        private BackgroundWorker _fackWorker = new BackgroundWorker();
        private object _LockTab = new object();
        private object _LockTabLoad = new object();

        private Canvas tabStyleGroup1;
        private Canvas tabStyleGroup2;
        private Canvas tabStyleGroup3;
        private Canvas tabStyleGroup4;
        private Canvas tabStyleGroup5;
        private Canvas tabStyleGroup6;
        private Canvas tabStyleGroup7;
        private Canvas[] tabStyleCollection;
        private Image[] tabIamgeStatusCollection;
        private bool[] tabComplateState;
        #endregion

        #region Constructor

        public QuestionContainerPage()
        {
            InitializeComponent();

            // Load Question Group header
            this.cvsQuestionGroupContainer.Children.Clear();
            this.cvsQuestionGroupContainer.Children.Add(this.QuestionGroupHeaderControl);
            this.cvsQuestionGroupContainer.UpdateLayout();

            // Load default question group
            LoadQuestionGroup(0);


            this.LoadingFadeOut.Begin();
            this.Loaded += new RoutedEventHandler(QuestionContainerPage_Loaded);


            this.QuestionGroupHeaderControl.ValidateConfirmationNotify += new EventHandler<HCI.Questionaire.EventArgument.ValidateConfirmationNotifyArgs>(QuestionGroupHeaderControl_ValidateConfirmationNotify);
            this.QuestionGroupHeaderControl.LastMoveNextInQuestionGroup += new Action<int>(QuestionGroupHeaderControl_LestMoveInQuestionGroup);
            this.QuestionGroupHeaderControl.LastMovePreviousInQuestionGroup += new Action<int>(QuestionGroupHeaderControl_LastMovePreviousInQuestionGroup);

            this.QuestionGroupHeaderControl.LastMoveNextInQuestionGroupMouseEnter += new Action<int>(QuestionGroupHeaderControl_LastMoveNextInQuestionGroupMouseEnter);
            this.QuestionGroupHeaderControl.LastMoveNextInQuestionGroupMouseLeave += new Action<int>(QuestionGroupHeaderControl_LastMoveNextInQuestionGroupMouseLeave);
            this.QuestionGroupHeaderControl.LastPreviousMoveInQuestionGroupMouseEnter += new Action<int>(QuestionGroupHeaderControl_LastPreviousMoveInQuestionGroupMouseEnter);
            this.QuestionGroupHeaderControl.LastPreviousMoveInQuestionGroupMouseLeave += new Action<int>(QuestionGroupHeaderControl_LastPreviousMoveInQuestionGroupMouseLeave);

            _fackWorker.DoWork += new DoWorkEventHandler(_fackWorker_DoWork);
            _fackWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_fackWorker_RunWorkerCompleted);

        }

        void QuestionGroupHeaderControl_ValidateConfirmationNotify(object sender, HCI.Questionaire.EventArgument.ValidateConfirmationNotifyArgs e)
        {
            var groupNotify = (IQuestionGroup)sender;

            string imagePath = e.IsComplete ? "../images/inCollectionFieldPin.png" : "../images/field.png";
            this.tabIamgeStatusCollection[groupNotify.GroupIndex].Source = new BitmapImage(new Uri(imagePath, UriKind.Relative));
            this.tabComplateState[groupNotify.GroupIndex] = e.IsComplete;

            bool showConfirm = true;
            foreach (var item in this.tabComplateState)
            {//btnConfirm
                if (!item)
                {
                    showConfirm = false;
                    break;
                }
            }

            this.btnConfirm.Visibility = showConfirm ? Visibility.Visible : Visibility.Collapsed;
        }

        void QuestionGroupHeaderControl_LastPreviousMoveInQuestionGroupMouseLeave(int obj)
        {
            this.tabWouldSelect.Stop();
        }

        void QuestionGroupHeaderControl_LastPreviousMoveInQuestionGroupMouseEnter(int currentGroupIndex)
        {
            if (currentGroupIndex <= 0)
                return;

            this.tabWouldSelect.Stop();
            //this.tabDeselect.Stop();

            var targetCanvas = this.tabStyleCollection[currentGroupIndex - 1];
            Storyboard.SetTarget(this.tabWouldSelect, targetCanvas.Children[1]);
            this.tabWouldSelect.Begin();
        }

        void QuestionGroupHeaderControl_LastMovePreviousInQuestionGroup(int currentQuestionGroup)
        {
            if (currentQuestionGroup <= 0)
                return;

            // Force load question next group 
            this.LoadQuestionGroup(currentQuestionGroup - 1);
            this.LoadQuestionGroupAnimation(this.tabStyleCollection[currentQuestionGroup - 1]);
        }

        void QuestionGroupHeaderControl_LestMoveInQuestionGroup(int currentQuestionGroup)
        {
            if (currentQuestionGroup + 1 >= this.tabStyleCollection.Length)
                return;

            // Force load question next group 
            this.LoadQuestionGroup(currentQuestionGroup + 1);
            this.LoadQuestionGroupAnimation(this.tabStyleCollection[currentQuestionGroup + 1]);
        }
        void QuestionGroupHeaderControl_LastMoveNextInQuestionGroupMouseLeave(int currentGroupIndex)
        {
            this.tabWouldSelect.Stop();
        }

        void QuestionGroupHeaderControl_LastMoveNextInQuestionGroupMouseEnter(int currentGroupIndex)
        {
            if (currentGroupIndex + 1 >= this.tabStyleCollection.Length)
                return;

            this.tabWouldSelect.Stop();
            //this.tabDeselect.Stop();

            var targetCanvas = this.tabStyleCollection[currentGroupIndex + 1];
            Storyboard.SetTarget(this.tabWouldSelect, targetCanvas.Children[1]);
            this.tabWouldSelect.Begin();
        }

        void _fackWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Loading.Stop();
            this.LoadingFadeOut.Stop();
            this.LoadingFadeOut.Begin();
        }

        void _fackWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            System.Threading.Thread.Sleep(1500);
        }

        void QuestionContainerPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.tabStyleCollection = new Canvas[7];
            this.tabIamgeStatusCollection = new Image[7];

            this.tabIamgeStatusCollection[0] = this.tabImageStatus1;
            this.tabIamgeStatusCollection[1] = this.tabImageStatus2;
            this.tabIamgeStatusCollection[2] = this.tabImageStatus3;
            this.tabIamgeStatusCollection[3] = this.tabImageStatus4;
            this.tabIamgeStatusCollection[4] = this.tabImageStatus5;
            this.tabIamgeStatusCollection[5] = this.tabImageStatus6;
            this.tabIamgeStatusCollection[6] = this.tabImageStatus7;

            this.tabComplateState = new bool[7];
            this.tabComplateState[0] = false;
            this.tabComplateState[1] = false;
            this.tabComplateState[2] = false;
            this.tabComplateState[3] = false;
            this.tabComplateState[4] = false;
            this.tabComplateState[5] = false;
            this.tabComplateState[6] = false;

        }


        #endregion

        #region Property
        private QuestionGroupHeader QuestionGroupHeaderControl
        {
            get
            {
                if (_QuestionGroupHeaderControl == null)
                {
                    _QuestionGroupHeaderControl = new QuestionGroupHeader();
                }
                return _QuestionGroupHeaderControl;
            }

        }
        #endregion

        #region Method
        private void LoadQuestionGroup(int quextionGroupIndex)
        {
            try
            {
                this.QuestionGroupHeaderControl.LoadQuestionGroup(quextionGroupIndex);

                this.txtQuestionGroupDescription.FontSize = quextionGroupIndex == 0 ?26.5 : 30;
                this.txtQuestionGroupDescription.Text = this.QuestionGroupHeaderControl.CurrentQuestionGroup.Description;

                this.txtQuestionGroupInstruction.Text = this.QuestionGroupHeaderControl.CurrentQuestionGroup.Instruction;
                this.txtQuestionGroupInstruction.FontSize = quextionGroupIndex == 4 ? 18.5 : quextionGroupIndex == 5 ? 20: 23;

                panelShine.Begin();
            }
            finally
            {

            }
        }


        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

        }
        #endregion

        #region DropDown List Control
        private void _leaguesDropButton_Click(object sender, RoutedEventArgs e)
        {
            //if (this._leaguesListBox.Visibility == Visibility.Collapsed)
            //{
            //    this._leaguesListBox.Visibility = Visibility.Visible;
            //}
            //else
            //{
            //    this._leaguesListBox.Visibility = Visibility.Collapsed;
            //}
        }

        private void _leaguesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //this._leaguesListBox.Visibility = Visibility.Collapsed;

            //int leagueID = Convert.ToInt32(((League)((ListBox)sender).SelectedItem).LeagueID);
            //if (leagueID < 0)
            //{
            //    this.CreateServiceClient().GetMyFieldsAsync();
            //    this._selectedLeagueLabel.Text = "<My Fields>";
            //    this._leagueNameLabel.Text = "My";
            //}
            //else
            //{
            //    SiteServiceClient client = this.CreateServiceClient();
            //    client.GetFieldsForLeagueAsync(leagueID);
            //    client.GetLeagueAsync(leagueID);
            //    this._viewLeagueMethod.InvokeSelf(leagueID);
            //}

            //this._clearDirectionsMethod.InvokeSelf();
            //this._viewContactsMethod.InvokeSelf(false);
            //this._highlightFieldTab();
            //this.Loading.Begin();
            //this.LoadingFadeOut.Stop();
            //this.LoadingFadeIn.Begin();
        }
        #endregion

        #region Tab Events
        private void _viewFieldClick(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement element = ((FrameworkElement)sender);
            if (string.IsNullOrEmpty(element.Tag.ToString()))
            {
                throw new UnExpectException("Setting in tab button not correct");
            }

            this.LoadQuestionGroup(int.Parse(element.Tag.ToString()));
        }
        #endregion

        #region Animation Event Handlers

        private void _tab_Loaded(object sender, EventArgs e)
        {
            if (((Canvas)sender).Parent == this.tabQuestionGroup1)
            {
                this._fieldTab = (Canvas)sender;
                this._currentTab = (Canvas)sender;
                Storyboard.SetTarget(this.tabSelect, ((Canvas)sender).Children[1]);
                this.tabSelect.Begin();
            }
        }

        private void _tab_MouseEnter(object sender, MouseEventArgs e)
        {
            if (this._currentTab != sender)
            {
                this.tabMouseOver.Stop();
                Storyboard.SetTarget(this.tabMouseOver, ((Canvas)sender).Children[1]);
                this.tabMouseOver.Begin();
            }
        }

        private void _tab_MouseLeave(object sender, MouseEventArgs e)
        {
            if (this._currentTab != sender)
            {
                this.tabMouseOut.Stop();
                Storyboard.SetTarget(this.tabMouseOut, ((Canvas)sender).Children[1]);
                this.tabMouseOut.Begin();
            }
        }

        private void FackWorking()
        {
            this.LoadingFadeIn.Stop();
            this.LoadingFadeIn.Begin();
            this.Loading.Stop();
            this.Loading.Begin();
            while (!this._fackWorker.IsBusy)
            {
                this._fackWorker.RunWorkerAsync();
            }

        }
        private void _tab_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            LoadQuestionGroupAnimation((Canvas)sender);
        }

        private void LoadQuestionGroupAnimation(Canvas sender)
        {
            lock (_LockTab)
            {
                try
                {
                    FackWorking();

                    if (this._currentTab != sender)
                    {
                        this.tabMouseOver.Stop();
                        this.tabMouseOut.Stop();
                        if (this._currentTab != null)
                        {
                            this.tabDeselect.Stop();
                            Storyboard.SetTarget(this.tabDeselect, this._currentTab.Children[1]);
                            this.tabDeselect.Begin();
                        }
                        this.tabSelect.Stop();
                        Storyboard.SetTarget(this.tabSelect, sender.Children[1]);
                        this.tabSelect.Begin();
                        this._currentTab = sender;
                    }

                    //System.Threading.Thread.Sleep(1500);
                }
                finally
                {

                }
            }
        }

        private void _field_MouseEnter(object sender, MouseEventArgs e)
        {
            this.fieldMouseOver.Stop();
            Storyboard.SetTarget(this.fieldMouseOver, (DependencyObject)sender);
            this.fieldMouseOver.Begin();
        }

        private void _field_MouseLeave(object sender, MouseEventArgs e)
        {
            this.fieldMouseOut.Stop();
            Storyboard.SetTarget(this.fieldMouseOut, (DependencyObject)sender);
            this.fieldMouseOut.Begin();
        }

        private void panelMyFields_Loaded(object sender, RoutedEventArgs e)
        {
            //this.panelShine.Begin();
        }

        private void loadingThrobber_Loaded(object sender, RoutedEventArgs e)
        {
            //this.Loading.Begin();
        }

        private void LoadingFadeOut_Completed(object sender, EventArgs e)
        {
            //this.Loading.Stop();
        }

        private void HighlightFieldTab()
        {
            if (this._fieldTab != this._currentTab)
            {
                this.tabMouseOver.Stop();
                this.tabMouseOut.Stop();
                if (this._currentTab != null)
                {
                    this.tabDeselect.Stop();
                    Storyboard.SetTarget(this.tabDeselect, this._currentTab.Children[1]);
                    this.tabDeselect.Begin();
                }
                this.tabSelect.Stop();
                Storyboard.SetTarget(this.tabSelect, this._fieldTab.Children[1]);
                this.tabSelect.Begin();
                this._currentTab = this._fieldTab;
            }
        }
        #endregion

        #region EventHandler: Tab click
        private void tabQuestionGroup_Click(object sender, RoutedEventArgs e)
        {
            lock (_LockTab)
            {
                FrameworkElement element = ((FrameworkElement)sender);
                if (string.IsNullOrEmpty(element.Tag.ToString()))
                {
                    throw new UnExpectException("Setting in tab button not correct");
                }

                // Load Question group control
                var quextionGroupIndex = int.Parse(element.Tag.ToString());
                LoadQuestionGroup(quextionGroupIndex);
            }
        }
        #endregion

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            PopupDialog(sender, "ท่านต้องการออกจากแบบสอบถาม ?", "ตกลง", "ยกเลิก");
        }

        private void PopupDialog(object sender, string body, string firstButtonText, string seccoundButtonText)
        {
            // open popup
            // get starting position for animation: origin = middle of the clicked button
            GeneralTransform gt = ((Button)sender).TransformToVisual(this);
            Point offset = gt.Transform(new Point(0, 0));
            double OriginX = offset.X + (((Button)sender).ActualWidth / 2);  // middle postion: + width/2
            double OriginY = offset.Y + (((Button)sender).ActualHeight / 2);  // middle postion: + height/2

            // get destination: middle of the app

            double DestinationX = this.ActualWidth / 2;
            double DestinationY = this.ActualHeight / 2;

            // add the control to the main grid, & make it stretch over the full page size.
            // Animations etc are generated by the popup's constructor

            var pop = new PopupDialog(OriginX, OriginY, DestinationX, DestinationY);
            pop.BodyText = body;
            pop.FirstButtonText = firstButtonText;
            pop.SecoundButtonText = seccoundButtonText;
            pop.FirstButtonCliked += new RoutedEventHandler(pop_FirstButtonCliked);
            pop.SecoundButtonCliked += new RoutedEventHandler(pop_SecoundButtonCliked);

            pop.SetValue(Grid.RowSpanProperty, 3);
            pop.SetValue(Grid.ColumnSpanProperty, 3);

            this.LayoutRoot.Children.Add(pop);
        }

        void pop_SecoundButtonCliked(object sender, RoutedEventArgs e)
        {
            ((PopupDialog)sender).ClosePopup();
        }

        void pop_FirstButtonCliked(object sender, RoutedEventArgs e)
        {
            //TODO: Move to thank you page
            //((PopupDialog)sender).ClosePopup();

            this.NavigationService.Navigate(new Uri("/TitlePage?exit=1", UriKind.RelativeOrAbsolute));
        }

        private void tabStyleGroup1_Loaded(object sender, RoutedEventArgs e)
        {
            this.tabStyleGroup1 = (Canvas)sender;
            this.tabStyleCollection[0] = this.tabStyleGroup1;

            this._fieldTab = this.tabStyleGroup1;
            this._currentTab = this.tabStyleGroup1;
            Storyboard.SetTarget(this.tabSelect, this.tabStyleGroup1.Children[1]);
            this.tabSelect.Begin();
        }
        private void tabStyleGroup2_Loaded(object sender, RoutedEventArgs e)
        {
            this.tabStyleGroup2 = (Canvas)sender;
            this.tabStyleCollection[1] = this.tabStyleGroup2;
        }
        private void tabStyleGroup3_Loaded(object sender, RoutedEventArgs e)
        {
            this.tabStyleGroup3 = (Canvas)sender;
            this.tabStyleCollection[2] = this.tabStyleGroup3;
        }
        private void tabStyleGroup4_Loaded(object sender, RoutedEventArgs e)
        {
            this.tabStyleGroup4 = (Canvas)sender;
            this.tabStyleCollection[3] = this.tabStyleGroup4;
        }
        private void tabStyleGroup5_Loaded(object sender, RoutedEventArgs e)
        {
            this.tabStyleGroup5 = (Canvas)sender;
            this.tabStyleCollection[4] = this.tabStyleGroup5;
        }
        private void tabStyleGroup6_Loaded(object sender, RoutedEventArgs e)
        {
            this.tabStyleGroup6 = (Canvas)sender;
            this.tabStyleCollection[5] = this.tabStyleGroup6;
        }
        private void tabStyleGroup7_Loaded(object sender, RoutedEventArgs e)
        {
            this.tabStyleGroup7 = (Canvas)sender;
            this.tabStyleCollection[6] = this.tabStyleGroup7;
        }

        private void btnConfirm_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.PopupDialog(sender, "ขอบคุณที่ให้ความร่วมมือในการตอบแบบสอบถาม", "ตกลง", "ยกเลิก");
        }

        //private void btnConfirm_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
        //{
        //    this.PopupDialog(sender, "ขอบคุณที่ให้ความร่วมมือในการตอบแบบสอบถาม", "ตกลง", "ยกเลิก");
        //}
    }
}
